#include "Socket.hpp"
#include <unistd.h>
#include <sys/types.h>

// ./test_svr.exe server_port
int main(int argc, char* argv[]){
    if(argc != 2) return -1;

    uint16_t server_port = std::stoi(argv[1]);
    Socket server_socket;
    server_socket.CreateServer(server_port, "0.0.0.0", true);

    while(1){

        int fd = server_socket.Accept();
        Socket s(fd);

        if(fd < 0){
            if(errno == EWOULDBLOCK || errno == EAGAIN || errno == EINTR)  continue;
            return -1;
        }

        //创建子进程进行读取操作
        pid_t id = fork();
        if(id < 0){}
        else if(id == 0){
            if(fork() > 0) exit(0);

            //孙子进程 -> 孤儿进程
            while(1){
                char buffer[1024] = {0};
                ssize_t n = s.Recv(buffer, sizeof(buffer) - 1);
                if(n < 0){
                    //小于0 -> 真的出错了
                    if(errno == ECONNRESET) std::cout << "客户端退出" << std::endl;
                    break;
                }
                else if(n == 0) {
                    //不一定是客户端退出：
                    //阻塞的情况下来看，确实是
                    //如果是非阻塞，返回0的时候就不是客户端退出
                    if(errno == EAGAIN || errno == EINTR || errno == EWOULDBLOCK) continue;
                    break;
                }
                else{
                    buffer[n] = 0;
                    std::cout << buffer << std::endl;
                    //然后处理发送回去
                    std::string ret = "echo : ";
                    ret += buffer;
                    n = s.Send((void*)ret.c_str(), ret.size());
                }
            }
        }
    }
    return 0;
}